# !usr/bin/env python
# -*- coding:utf-8 -*-

'''
 Description  : 
 Version      : 1.0
 Author        : qww
 Date         : 2021-05-02 16:57:13
 LastEditors  : qww
 LastEditTime : 2021-05-02 19:32:00
'''

import json
import os
import time
import uuid
from flask import request
from flask import Blueprint
from settings import ApplicationConfig
from static.model.predict import predict
from result_data.result_data import upload_result, FailCode, SuccessCode


identification_bp = Blueprint('identification', __name__)
ALLOWED_EXTENSIONS = ApplicationConfig.ALLOWED_EXTENSIONS
BASE_DIR = os.path.join(os.path.join(os.getcwd(), 'static'))
FILE_DIR = os.path.join(BASE_DIR, 'img')
MODEL_PATH = os.path.join(os.path.join(BASE_DIR, 'model'), 'model.pth')


# 判断文件是否合法
def __allowed_file(filename):
    return filename.rsplit('.', 1)[-1].lower() in ALLOWED_EXTENSIONS


@identification_bp.route("/identification/upload", methods=['POST'])
def upload():
    f = request.files['img']
    filename = f.filename
    if not __allowed_file(filename):
        upload_result['code'] = FailCode.FAIL_UPLOAD
        upload_result['msg'] = "文件上传失败"
        return json.dumps(upload_result, indent=2, ensure_ascii=False)
    ext = filename.rsplit('.', 1)[-1]
    unix_time = int(time.time())
    new_filename = str(uuid.uuid1()).replace('-', '') + str(unix_time) + '.' + ext

    f.save(os.path.join(FILE_DIR, new_filename))
    upload_result['code'] = SuccessCode.SUCCESS_UPLOAD
    upload_result['msg'] = "文件上传成功"
    # 模型识别
    upload_result['data'] = predict(filename=os.path.join(FILE_DIR, new_filename),
                                    model_path=MODEL_PATH)
    return json.dumps(upload_result, indent=2, ensure_ascii=False)

